<?php if(!defined('BASEPATH')) exit('No direct script access allowed!');

class Questions_Share_Model extends grocery_CRUD_Model {
	
	protected $question_id=0;
	
	public function lists_array($subject_id, $question_id){
		if($subject_id != 0 && $question_id !=0){
			$this->question_id = $question_id;
			
			$this->db->join('teachings','teachings.teacher_id = teachers.id');
			
			$this->db->where('subject_id',$subject_id);
			$rs = $this->db->get('teachers')->result_array();
			//echo $this->db->last_query();
			$data = array();
			$data[0] = '';
			foreach($rs as $row){
				$data[ $row['teacher_id'] ] = $row['name'];
			}
			
		}
		else{
			$data ['ERROR'] = 'Belum ada data pembagian mengajar';
		}
		return $data;
	}

	function db_update($post_array, $primary_key_value)
    {
		$CI =& get_instance();
		$CI->load->model('teachers_model','teachers');
		$teachers = $CI->teachers->get_by_name($post_array['name']);
		
		
		/*
		echo var_dump($post_array);
		$this->db->query('CREATE TEMPORARY TABLE tmp SELECT * FROM questions WHERE id = ' . $this->question_id);
		$this->db->query('UPDATE tmp SET id = ' . ($this->question_id + 1). ' WHERE id = '. $this->question_id);
		$this->db->query('INSERT INTO questions SELECT * FROM tmp WHERE id = ' . ($this->question_id + 1));
		*/
		//echo $this->db->last_query();
		$this->db->where('id',$this->question_id);
		$rs = $this->db->get('questions')->result_array();
		$rs = $rs[0];
		$data['school_year_id'] = $rs['school_year_id'];
		$data['chapter_name'] = $rs['chapter_name'];
		$data['teacher_id'] = $post_array['name'];
		$data['create_date'] = date('Y-m-d');
		$data['create_time'] = date('H:i:s');
		$data['qty'] = $rs['qty'];
		$data['create_ip'] = $_SERVER['REMOTE_ADDR'];
		$data['last_update_date'] = date('Y-m-d');
		$data['information'] = $rs['information'];
		$data['visibility'] = 0;
		
		$insert = $this->db->insert('questions',$data);
		$question_id = '';
    	if($insert)
    	{
    		$question_id = $this->db->insert_id();
    	}
		
		//---------------------- INSERT INTO QUESTION DETAIL --------------------------
		$this->db->where('question_id',$this->question_id);
		$rs = $this->db->get('questions_detail')->result_array();
		echo $this->db->last_query();
		$data=array();
		foreach($rs as $row){
			$data['question_id'] = $question_id;
			$data['original_number'] = $row['original_number'];
			$data['problem'] = $row['problem'];
			$data['option_a'] = $row['option_a'];
			$data['option_b'] = $row['option_b'];
			$data['option_c'] = $row['option_c'];
			$data['option_d'] = $row['option_d'];
			$data['option_e'] = $row['option_e'];
			$data['answer'] = $row['answer'];
			$insert = $this->db->insert('questions_detail',$data);
		}
		
		if($insert && $question_id){
			//redirect('questions/questions_display');
			return true;
		}
		else
			return false;
    }
	
}
